import { Module, ValidationPipe, MiddlewareConsumer, NestModule } from '@nestjs/common';
import { ConfigModule, ConfigService as NestConfigService } from '@nestjs/config';
import cozeConfig from './config/coze.config';
import { TypeOrmModule } from '@nestjs/typeorm';
import { ThrottlerModule } from '@nestjs/throttler';
import { WinstonModule } from 'nest-winston';
import { APP_GUARD, APP_INTERCEPTOR, APP_PIPE, APP_FILTER } from '@nestjs/core';
import { AuthModule, JwtAuthGuard, RolesGuard } from '@app/auth';
import { ResponseInterceptor } from '@app/common';
import { HealthModule } from '@app/health';
import { GlobalExceptionFilter } from './filters/global-exception.filter';
import { AuthController } from './controllers/auth.controller';
import { PostsController } from './controllers/posts.controller';
import { UsersController } from './controllers/users.controller';
import { SystemController } from './controllers/system.controller';
import { DashboardController } from './controllers/dashboard.controller';
import { CategoriesController } from './controllers/categories.controller';
import { TagsController } from './controllers/tags.controller';
import { UploadController } from './controllers/upload.controller';
import { AnnouncementsController } from './controllers/announcements.controller';
import { AppController } from './app.controller';
import { AppService } from './app.service';
import { getKvAdminDatabaseConfig, ConfigService as AppConfigService } from '@app/config';
import { getRedisConfig } from './config/redis.config';
import { getLoggerConfig } from './config/logger.config';
import * as entities from '@app/entities';
import { UsersService } from './services/users.service';
import { BlogsService } from './services/blogs.service';
import { TagsService } from './services/tags.service';
import { AnnouncementsService } from './services/announcements.service';
import { RedisService } from './services/redis.service';
import { UploadProxyService } from './services/upload-proxy.service';
import { LoggerMiddleware } from './middleware/logger.middleware';
import { RequestIdMiddleware } from './middleware/request-id.middleware';
import { CustomThrottlerGuard } from './guards/throttle.guard';
import { TimeoutInterceptor } from './interceptors/timeout.interceptor';
import { CozeController } from './controllers/coze.controller';
import { CozeService } from './services/coze.service';

@Module({
  imports: [
    ConfigModule.forRoot({
      isGlobal: true,
      envFilePath: ['.env.production', '.env.development', '.env'],
      load: [cozeConfig],
    }),
    TypeOrmModule.forRootAsync({
      imports: [ConfigModule],
      useFactory: (nestConfig: NestConfigService) => {
        const appConfig = new AppConfigService(nestConfig as any);
        const opts: any = getKvAdminDatabaseConfig(appConfig);
        if (opts && 'name' in opts) delete opts.name; // use default connection
        return opts;
      },
      inject: [NestConfigService],
    }),
    TypeOrmModule.forFeature(Object.values(entities)),
    ThrottlerModule.forRootAsync({
      imports: [ConfigModule],
      useFactory: (configService: NestConfigService) => [{
        ttl: 60, // 时间窗口：60秒
        limit: 100, // 限制：100次请求
      }],
      inject: [NestConfigService],
    }),
    WinstonModule.forRootAsync({
      imports: [ConfigModule],
      useFactory: (configService: NestConfigService) => getLoggerConfig(configService),
      inject: [NestConfigService],
    }),
    AuthModule.forRoot(),
    HealthModule,
  ],
  controllers: [
    AppController,
    AuthController,
    PostsController,
    UsersController,
    SystemController,
    DashboardController,
    CozeController,

    CategoriesController,
    TagsController,
    UploadController,
    AnnouncementsController
  ],
  providers: [
    AppService,
    UsersService,
    BlogsService,
    TagsService,
    AnnouncementsService,
    RedisService,
    UploadProxyService,
    CozeService,
    { provide: APP_INTERCEPTOR, useClass: ResponseInterceptor },
    { provide: APP_INTERCEPTOR, useClass: TimeoutInterceptor },
    { provide: APP_GUARD, useClass: CustomThrottlerGuard },
    { provide: APP_GUARD, useClass: JwtAuthGuard },
    { provide: APP_GUARD, useClass: RolesGuard },
    { provide: APP_FILTER, useClass: GlobalExceptionFilter },
    {
      provide: APP_PIPE,
      useFactory: () =>
        new ValidationPipe({
          whitelist: true,
          transform: true,
          forbidNonWhitelisted: true,
          transformOptions: { enableImplicitConversion: true },
        }),
    },
  ],
})
export class AppModule implements NestModule {
  configure(consumer: MiddlewareConsumer) {
    consumer
      .apply(RequestIdMiddleware, LoggerMiddleware)
      .forRoutes('*');
  }
}


